package org.farm2.main.cecurity.service;

import org.farm2.base.domain.FarmUserContext;
import org.farm2.base.domain.FarmUserContextLoader;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义权限校验方法，作用在controller注解上
 */
@Component("farmAction")
public class FarmActionCheck {
    public boolean has(String... keys) {
        FarmUserContext userContext = FarmUserContextLoader.getCurrentUser();
        if (userContext != null && userContext.getType().equals("3")) {
            //管理员有权限
            return true;
        }
        List<String> userkeys = null;
        if (userContext == null) {
            userkeys = new ArrayList<>();
        } else {
            userkeys = userContext.getActions();
        }
        //检索权限所有用户都有
        userkeys.addAll(List.of("search*", "wknow*", "wknow*", "wtag*", "resourcefile*", "wchat*"));
        for (String key : keys) {
            for (String actionKey : userkeys) {
                // 将通配符模式转换为正则表达式
                String regex = actionKey.toUpperCase().replace("*", ".*");
                if (key.trim().toUpperCase().matches(regex)) {
                    return true;
                }
            }
        }
        return false;
    }
}
